<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" @change="handleQuery">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:announcement:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:announcement:edit']"
        >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:announcement:remove']"
        >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="intellectualPropertyList"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="left" prop="title" width="500px" />
      <el-table-column label="内容" align="center" prop="content">
        <template slot-scope="scope">
          <el-popover popper-class="my-popper" trigger="click" placement="top">
            <div v-html="scope.row.content"></div>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" class="pointer">查看详情</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="拟稿人" align="center" prop="createBy" />
      <!-- 状态 -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.status === 2" type="danger">未通过</el-tag>
        </template>
      </el-table-column>
      <!-- 审核结果 -->
      <el-table-column
        label="审核详情"
        align="center"
        prop="auditResult"
        width="100px"
      >
        <template slot-scope="scope">
          <el-popover popper-class="popper" trigger="click" placement="top">
            <!-- 审核人 -->
            <div>审核人:{{ scope.row.reviewer }}</div>
            <div class="flex" v-if="scope.row.status === 2">
              <div class="label">备注:</div>
              <div class="comment" v-html="scope.row.comment"></div>
            </div>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" class="pointer">点击查看</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        width="200px"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- 审核 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:announcement:edit']"
          >审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:announcement:edit']"
          >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:announcement:remove']"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 审核表单 -->
    <el-dialog
      title="审核"
      :visible.sync="openAudit"
      width="80%"
      append-to-body
    >
      <el-form ref="form" :model="auditForm" :rules="rules" label-width="80px">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="审核备注"
          prop="remark"
          v-if="auditForm.status === 2"
        >
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            placeholder="请输入审核备注"
          />
        </el-form-item>
        <el-button class="bt" type="primary" @click="changeStatus()"
        >确定</el-button
        >
      </el-form>
    </el-dialog>

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <web-editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="上传附件" prop="attach">
          <el-upload
            class="upload-demo"
            action="/prod-api/file/upload"
            :on-remove="handleRemove"
            :on-change="handleChange"
            multiple
            :limit="20"
            :on-exceed="handleExceed"
            :file-list="uploadedFileList"
            :headers="{ Authorization: getToken() }"
            :on-preview="handlePreview"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listAnnouncement,
  getAnnouncement,
  delAnnouncement,
  addAnnouncement,
  updateAnnouncement,
} from "@/api/system/announcement";
import { getToken } from "@/utils/auth";
import { uploadFile } from "@/api/system/file.js";
import { updateAnnouncementStatus } from "../../../api/system/announcement";

export default {
  name: "IntellectualPropertyRegulations",
  data() {
    // 内容校验规则
    const validateContent = (rule, value, callback) => {
      const strippedContent = value ? value.replace(/<[^>]+>/g, '').trim() : '';
      if (!value || strippedContent.length === 0) {
        callback(new Error('内容不能为空'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      intellectualPropertyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示审核弹出层
      openAudit: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        title: null,
        content: null,
        type: '16', // 知识产权法规类型
        status: null,
      },
      // 表单参数
      form: {},
      auditForm: {
        id: null,
        status: 1,
        comment: "",
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { min: 1, max: 100, message: "标题长度必须在1到100个字符之间", trigger: "blur" }
        ],
        content: [
          { required: true, validator: validateContent, trigger: "blur" },
        ],
      },
      fileList: [],
      uploadedFileList: [],
      statusOptions: [
        { value: 0, label: "未审核" },
        { value: 1, label: "已审核" },
        { value: 2, label: "审核未通过" },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getToken() {
      return getToken();
    },
    // 文件上传
    handleChange(file, fileList) {
      this.fileList.push(file.raw);
    },
    handleRemove(file, fileList) {
      let index = this.fileList.indexOf(file.raw);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
      // 不止要删除fileRawList，还要删除已存在的文件列表
      let exitsIndex = this.uploadedFileList.findIndex(
        (item) => item.uid === file.uid
      );
      if (exitsIndex !== -1) {
        this.uploadedFileList.splice(exitsIndex, 1);
      }
    },
    handlePreview(file) {
      if (file.url) {
        // 只能预览已上传的文件
        const link = document.createElement("a");
        document.body.appendChild(link);
        link.style.display = "none"; // 隐藏起来
        link.href = file.url;
        link.target = "_blank"; // 在新窗口或标签页中打开链接
        link.click();
        document.body.removeChild(link);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 20 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    //审核状态修改
    changeStatus() {
      updateAnnouncementStatus(this.auditForm).then((response) => {
        this.$modal.msgSuccess("审核成功");
        this.openAudit = false;
        this.getList();
      });
    },
    /** 查询公告列表 */
    getList() {
      this.loading = true;
      listAnnouncement(this.queryParams).then((response) => {
        this.intellectualPropertyList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        files: null,
        type: '16', // 默认为知识产权法规
      };
      this.fileList = [];
      this.uploadedFileList = [];
      this.resetForm("form");
    },
    handleAudit(row) {
      this.auditForm.id = row.id;
      this.openAudit = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加知识产权法规";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAnnouncement(id).then((response) => {
        this.form = response.data;
        this.uploadedFileList = response.data.files ?? [];
        this.open = true;
        this.title = "修改知识产权法规";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.form.files = this.uploadedFileList;
          for (const file of this.fileList) {
            const formData = new FormData();
            formData.append("file", file);
            const res = await uploadFile(formData);
            if (res.code === 200) {
              const { name, url } = res.data;
              this.form.files.push({
                name,
                url,
              });
            }
          }
          if (this.form.id != null) {
            updateAnnouncement(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAnnouncement(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除所选的知识产权法规？")
        .then(function () {
          return delAnnouncement(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.flex {
  max-width: 500px;
  text-wrap-mode: wrap;
  display: flex;
  .label {
    width: 40px;
  }
}
.bt {
  width: 100%;
}
</style>
